package com.gitee.xmhzzz.component.shutdown.graceful.nacos;

import com.alibaba.cloud.nacos.registry.NacosAutoServiceRegistration;
import com.gitee.xmhzzz.component.shutdown.graceful.event.ApplicationShutdownEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.EventListener;

/**
 * @ClassName NacosShutdown
 * @Description
 * @Author wzq
 * @Date 2023/9/25 13:31
 * @Version 1.0
 */
@Slf4j
@ConditionalOnProperty(value = "xmhzzz.graceful.shutdown.enable", havingValue = "true")
public class NacosShutdown {
    private volatile boolean shutdown = false;


    @EventListener
    public void shutdownEventListener(ApplicationShutdownEvent applicationShutdownEvent) {
        try {
            if (!this.shutdown) {
                this.shutdown = true;
                Long beginTime = System.currentTimeMillis();
                log.info("nacos start beginTime [{}]", beginTime);
                ApplicationContext applicationContext = (ApplicationContext) applicationShutdownEvent.getSource();
                NacosAutoServiceRegistration nacosAutoServiceRegistration = applicationContext.getBean(NacosAutoServiceRegistration.class);
                nacosAutoServiceRegistration.stop();
                Long endTime = System.currentTimeMillis() - beginTime;
                log.info("nacos shutdown time total(ms):{} ", endTime);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

    }
}
